package me.zhengjie.resources.config;

import com.alibaba.fastjson.JSON;
import org.apache.http.entity.ContentType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 *
 */
@Component
public class AuthExceptionEntryPoint implements AuthenticationEntryPoint {


    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException)
            throws ServletException {

        try {
            Map<String, String> map = new HashMap();
            map.put("error", "401");
            map.put("message", "token过期，请重新登陆");
            map.put("path", request.getServletPath());
            map.put("timestamp", String.valueOf(System.currentTimeMillis()));

            response.setContentType(ContentType.APPLICATION_JSON.toString());
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write(JSON.toJSONString(map));
        } catch (Exception e) {
            throw new ServletException();
        }
    }

}


